
(function (w) {
  function ajax(option) {
    if (!option.url) return;
    option.method = option.method && option.method.toUpperCase() || 'GET';
    option.timeout = option.timeout || 0;
    option.data = JSON.stringify(option.data) || null;
    let xhr = null, timer = null;
    if (w.XMLHttpRequest) {
      xhr = new XMLHttpRequest()
    } else {
      xhr = new ActiveXObject('Microsoft.XMLHTTP');
    }
    xhr.onreadystatechange = function () {
      if (xhr.readyState !== 4) return;
      clearTimeout(timer);
      if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {
        option.success && option.success(JSON.parse(xhr.responseText));
      } else {
        option.error && option.error(xhr.status)
      }
    }
    if (option.method === 'GET') {
      const params = option.params && toUrl(option.params) || '';
      option.url += params;
      xhr.open('GET', option.url, true);
      xhr.send()
    } else {
      xhr.open(option.method, option.url, true);
      xhr.setRequestHeader('Content-Type', 'application/json');
      xhr.send(option.data);
    }
    if (option.timeout) {
      timer = setTimeout(() => {
        xhr.abort();
      }, option.timeout)
    }
    function toUrl(json) {
      let arr = [], str = '';
      for (let k in json) {
        str = `${k}=${json[k]}`;
        arr.push(str)
      }
      return '?' + encodeURIComponent(arr.join('&'))
    }
  }
  w.$ajax = ajax;
})(window)